package com.mexico.inloancash.http;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 作者：Alex
 * 时间：2017/7/23 15:05
 * 简述：
 */
class IndiaProgressRequestBody extends RequestBody {
    private RequestBody originalRequestBody;
    private IndiaOnUploadListener onUploadListener;
    private CountingSink countingSink;

    public IndiaProgressRequestBody setOnUploadListener(IndiaOnUploadListener onUploadListener) {
        this.onUploadListener = onUploadListener;
        return this;
    }

    public IndiaProgressRequestBody setOriginalRequestBody(RequestBody requestBody) {
        this.originalRequestBody = requestBody;
        return this;
    }


    @Override
    public MediaType contentType() {
        return originalRequestBody.contentType();
    }

    @Override
    public long contentLength() {
        try {
            return originalRequestBody.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        BufferedSink bufferedSink;
        countingSink = new CountingSink(sink);
        bufferedSink = Okio.buffer(countingSink);
        originalRequestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }

    protected final class CountingSink extends ForwardingSink {
        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            bytesWritten += byteCount;
            //listener.progress("正在上传", bytesWritten, contentLength());
            double progress = (bytesWritten * 100 / contentLength());
            //LogTrack.w("progress = " + progress);
            if (onUploadListener != null) {
                onUploadListener.onUploadProgress(contentLength(), bytesWritten, progress);
            }
        }
    }
}

